package com.message.client.form;

import com.message.client.util.ClientSocket;
import org.apache.commons.lang3.StringUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class StartUpForm extends JFrame {

    private JButton connectBtn;

    private JTextField connectHost;

    /**
     * 初始化form信息
     */
    private void initFormInfo() {
        this.setSize(500, 500);
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
    }

    /**
     * 初始化布局
     */
    private void initLayout() {
        JFrame thisForm = this;
        connectBtn = new JButton("connect");
        connectHost = new JTextField("localhost:8888");

        connectHost.setSize(200, 200);
        connectBtn.setSize(200, 200);

        connectBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                ClientSocket clientSocket = new ClientSocket();
                String[] arr = connectHost.getText().split(":");
                String host = arr[0];
                Integer port = Integer.parseInt(StringUtils.isNotBlank(arr[1]) ? arr[1] : "0");
                Boolean connectResult = clientSocket.testHost(host, port);

                if (connectResult) {
                    JOptionPane.showMessageDialog(null,
                            "连接成功！", "Connect result", JOptionPane.INFORMATION_MESSAGE);
                    new ChatMainForm(host, port);
                    thisForm.dispose();
                    return;
                }

                JOptionPane.showMessageDialog(null,
                        "连接失败！", "Connect result", JOptionPane.ERROR_MESSAGE);
            }
        });

        this.setLayout(new GridLayout(4, 3));
        this.add(connectHost);
        this.add(connectBtn);
    }

    public StartUpForm() {
        initLayout();
        initFormInfo();
    }
}
